<template>
  <div style="height: 100%">
    <el-container style="height: 100%">
      <div class="title-logo" :style="{ 'background-color': systemCcolor }">
        <!-- <img src="../../assets/img/logo.png"/> -->
        <h3 v-if="isCollapse">
          <i class="el-icon-eleme hideIcon" style="color: #1abc9c;" />
        </h3>
        <h3 v-if="!isCollapse" style="color: #1abc9c;margin: left 10px;">
          疫苗接种在线教育
        </h3>
      </div>
      <el-aside
        :width="isCollapse ? '64px' : '200px'"
        style="background-color: #ffffff;margin-top: 60px;"
      >
        <el-scrollbar style="width: 100%;height:100%;overflow-x:hidden;">
          <el-menu
            :collapse="isCollapse"
            class="el-menu-vertical-demo"
            background-color="#ffffff"
            text-color="#272727"
            active-text-color="#66b1ff"
            :router="true"
            :collapse-transition="false"
            :default-active="activePath"
          >
            <i
              v-if="isCollapse"
              @click="isCollapse = false"
              class="hideIcon el-icon-s-unfold"
              style="color: #1abc9c;"
            ></i>
            <i
              v-else
              @click="isCollapse = true"
              class="hideIcon el-icon-s-fold"
              style="color: #1abc9c;"
            ></i>
            <el-submenu
              v-for="(item, index) in menu"
              :key="item.id"
              :index="item.id"
            >
              <template slot="title">
                <i :class="item.iconImg" class="menu-ico"></i>
                <span>{{ item.name }}</span>
              </template>
              <!-- 第二层菜单-->
              <div v-for="(itemChild, index) in item.child" :key="itemChild.id">
                <el-menu-item
                  v-if="itemChild.child === undefined"
                  :index="itemChild.url"
                  @click="changeActivePath(itemChild.url)"
                  >{{ itemChild.name }}
                </el-menu-item>
                <!-- 第三层菜单-->
                <div
                  v-else
                  v-for="itChild in itemChild.child"
                  :key="itChild.id"
                >
                  <el-submenu :index="itemChild.id">
                    <template slot="title">{{ itemChild.name }}</template>
                    <el-menu-item
                      :index="itChild.url"
                      @click="changeActivePath(itChild.url)"
                      >{{ itChild.name }}
                    </el-menu-item>
                  </el-submenu>
                </div>
              </div>
            </el-submenu>
          </el-menu>
        </el-scrollbar>
      </el-aside>
      <!-- 系统头部 -->
      <el-container>
        <el-header
          class="header-style"
          :style="{ 'background-color': systemCcolor, height: '50px' }"
        >
          <!-- <div class="top-home">
            <i class="hideIcon el-icon-s-home"></i>
          </div> -->
          <div class="top-exit" title="退出系统">
            <i class="hideIcon el-icon-switch-button" @click="loginOut"></i>
          </div>
          <el-dropdown>
            <div class="top-right">
              <el-avatar :size="40" class="imgTitle">
                <img :src="avatarURL" />
              </el-avatar>
              <span class="nameClass">
                {{ userInfo.name }}
              </span>
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="editAvatar"
                >修改头像</el-dropdown-item
              >
              <el-dropdown-item @click.native="updatePwd"
                >修改密码</el-dropdown-item
              >
              <el-dropdown-item @click.native="updateUserInfo"
                >修改用户信息</el-dropdown-item
              >
              <el-dropdown-item
                ><el-color-picker
                  v-model="systemCcolor"
                  title="系统主题设置"
                ></el-color-picker
              ></el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-header>
        <!-- 修改头像模态框 -->
        <el-dialog
          title="修改头像"
          :visible.sync="editAvatarDialog"
          width="30%"
        >
          <el-row type="flex" justify="center">
            <div class="cropper">
              <vueCropper
                ref="cropper"
                :img="option.img"
                :outputSize="option.size"
                :outputType="option.outputType"
                :info="option.info"
                :full="option.full"
                :canMove="option.canMove"
                :canMoveBox="option.canMoveBox"
                :original="option.original"
                :autoCrop="option.autoCrop"
                :autoCropWidth="option.autoCropWidth"
                :autoCropHeight="option.autoCropHeight"
                :fixedBox="option.fixedBox"
                @realTime="realTime"
              ></vueCropper>
            </div>
            <div class="previewBox">
              <div :style="previews.div" class="preview">
                <img :src="previews.url" :style="previews.img" />
              </div>
              <el-row type="flex" justify="center">
                <el-upload
                  action=""
                  :show-file-list="false"
                  :auto-upload="false"
                  :on-change="uploadImg"
                >
                  <el-button size="mini" type="primary">更换头像</el-button>
                </el-upload>
              </el-row>
              <br />
              <el-row>
                <el-button
                  icon="el-icon-plus"
                  circle
                  size="mini"
                  @click="changeScale(1)"
                ></el-button>
                <el-button
                  icon="el-icon-minus"
                  circle
                  size="mini"
                  @click="changeScale(-1)"
                ></el-button>
                <el-button
                  icon="el-icon-download"
                  circle
                  size="mini"
                  @click="down('blob')"
                ></el-button>
                <el-button
                  icon="el-icon-refresh-left"
                  circle
                  size="mini"
                  @click="rotateLeft"
                ></el-button>
                <el-button
                  icon="el-icon-refresh-right"
                  circle
                  size="mini"
                  @click="rotateRight"
                ></el-button>
              </el-row>
            </div>
          </el-row>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="saveEditAvatar">确 定</el-button>
            <el-button @click="editAvatarDialog = false">取 消</el-button>
          </span>
        </el-dialog>
        <el-main style="background-color: #f5f5f5">
          <router-view class="content-style"></router-view>
        </el-main>
      </el-container>
    </el-container>

    <!-- 密码模态框 -->
    <el-dialog
      title="修改密码"
      :closeOnClickModal="pwdCloseOnClickModal"
      :visible.sync="pwdAddAndEditDialogFormVisible"
      :before-close="pwdAddAndEditClose"
      width="30%"
    >
      <el-form ref="pwdEditElForm" :model="pwdFormData" class="form">
        <el-form-item
          prop="oldPassword"
          label="旧密码："
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="pwdFormData.oldPassword"
            placeholder="请输入旧密码"
            style="width:90%"
            show-password
            clearable
            autosize
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="password"
          label="新密码："
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="pwdFormData.password"
            placeholder="请输入新密码"
            style="width:90%"
            show-password
            clearable
            autosize
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPwd">确 定</el-button>
        <el-button @click="pwdAddAndEditDialogFormVisible = false"
          >取 消</el-button
        >
      </span>
    </el-dialog>

    <!-- 用户信息模态框 -->
    <el-dialog
      :title="title"
      :closeOnClickModal="closeOnClickModal"
      :visible.sync="addAndEditDialogFormVisible"
      :before-close="handleDialogClose"
      width="30%"
    >
      <el-form ref="addAndEditElForm" :model="addAndEditFormData" class="form">
        <el-form-item
          prop="name"
          label="用户名："
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="addAndEditFormData.name"
            placeholder="请输入用户名"
            style="width:90%"
            type="text"
            clearable
            autosize
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="classId"
          label="班 级："
          :label-width="formLabelWidth"
        >
          <el-cascader
            @change="stuClassChange"
            :change-on-select="true"
            :props="defaultParams"
            :options="classNames"
            v-model="addAndEditFormData.classId"
            :clearable="true"
            style="width:90%"
            clearable
            autosize
          >
          </el-cascader>
        </el-form-item>
        <el-form-item
          prop="idCard"
          label="身份证号："
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="addAndEditFormData.idCard"
            placeholder="请输入身份证号"
            style="width:90%"
            type="number"
            min="0"
            clearable
            autosize
          ></el-input>
        </el-form-item>
        <el-form-item prop="phone" label="电话：" :label-width="formLabelWidth">
          <el-input
            v-model="addAndEditFormData.phone"
            placeholder="请输入电话"
            style="width:90%"
            type="number"
            min="0"
            clearable
            autosize
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="handleConfirmEvent('addAndEditElForm')"
          >确 定</el-button
        >
        <el-button @click="handleDialogClose">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { VueCropper } from "vue-cropper";
import Message from "element-ui/packages/message/src/main";

export default {
  name: "manager",
  components: {
    VueCropper
  },
  data() {
    return {
      systemCcolor: "#464c5b", // 系统主题设置
      userInfo: [],
      stu: [],
      tableData: [],
      isCollapse: false,
      activePath: "", // 当前激活菜单的index,存储在localStorage中
      // 模态框相关
      defaultParams: {
        label: "name",
        value: "id",
        children: "child"
      },
      classNames: [], // 班级数据
      title: "",
      closeOnClickModal: false,
      addAndEditDialogFormVisible: false,
      addAndEditFormData: {
        id: "",
        name: "",
        classId: "",
        oldPassword: "",
        password: "",
        phone: "",
        idCard: "",
        headImg: ""
      },
      formLabelWidth: "120px",
      // 菜单数组
      menu: [],
      // 修改密码相关
      pwdFormData: {
        oldPassword: "",
        password: ""
      },
      pwdCloseOnClickModal: false,
      pwdAddAndEditDialogFormVisible: false,

      // 头像相关参数
      // avatarURL: require("@/assets/img/w1.png"),
      avatarURL: "",
      editAvatarDialog: false,
      previews: {},
      option: {
        img: "", // 裁剪图片的地址
        info: true, // 裁剪框的大小信息
        outputSize: 1, // 剪切后的图片质量（0.1-1）
        full: true, // 输出原图比例截图 props名full
        outputType: "png", // 裁剪生成额图片的格式
        canMove: true, // 能否拖动图片
        original: false, // 上传图片是否显示原始宽高
        canMoveBox: true, // 能否拖动截图框
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 100,
        autoCropHeight: 100,
        fixedBox: true // 截图框固定大小
      },
      fileName: ""
    };
  },

  created() {
    // 初始化，加载用户信息和菜单
    this.init();
    // 菜单高亮记录
    this.activePath = window.localStorage.getItem("currentMenu");
  },

  methods: {
    init() {
      let userInfo = this.$store.state.userInfo;
      if (userInfo === null || userInfo.length === 0) {
        let item = localStorage.getItem("userInfo");
        userInfo = JSON.parse(item);
      }
      this.userInfo = userInfo;
      this.avatarURL = "/api" + userInfo.imgPath;
      // 获取菜单
      let routes = this.$store.state.routes;
      // 第一次进入时候是null，后面可能是空或者undefined
      if (routes === null || routes.length === 0) {
        let item = localStorage.getItem("routers");
        if (item === null || item === undefined) {
          this.getTreeMenu();
        } else if (typeof item[0] == "string") {
          this.getTreeMenu();
        } else {
          this.menu = JSON.parse(item);
          this.$store.commit("initRoutes", this.menu);
        }
      } else {
        this.menu = this.$store.state.routes;
      }
    },

    // 加载菜单
    getTreeMenu() {
      this.api.getApi("/menu/get/treeMenu").then(res => {
        if (res.data !== undefined) {
          this.menu = res.data;
          this.$store.commit("initRoutes", res.data);
        }
      });
    },

    // 点击的菜单变色
    changeActivePath(path) {
      localStorage.setItem("currentMenu", path);
      this.activePath = path;
    },

    // 修改用户头像
    editAvatar() {
      this.editAvatarDialog = true;
      this.option.img = this.avatarURL;
    },

    // 修改用户密码
    updatePwd() {
      this.pwdAddAndEditDialogFormVisible = true;
    },

    // 提交修改的密码
    submitPwd() {
      let url =
        "/updatePwd?id=" +
        this.userInfo.id +
        "&oldPwd=" +
        this.pwdFormData.oldPassword +
        "&newPwd=" +
        this.pwdFormData.password;
      this.api.getApi(url).then(e => {
        if (e.data.code === 200) {
          this.pwdAddAndEditDialogFormVisible = false;
          this.loginOut();
        }
      });
    },

    // 关闭密码弹框
    pwdAddAndEditClose() {
      this.pwdAddAndEditDialogFormVisible = false;
    },

    // 修改用户信息
    updateUserInfo() {
      // 查找班级信息
      this.api.getApi("/stu/class/get/treeData").then(e => {
        this.classNames = e.data;
      });
      this.title = "修改用户信息";
      this.addAndEditDialogFormVisible = true;
      this.$set(this.addAndEditFormData, "id", this.userInfo.id);
      this.$set(this.addAndEditFormData, "name", this.userInfo.name);
      this.$set(this.addAndEditFormData, "classId", this.userInfo.classId);
      this.$set(this.addAndEditFormData, "phone", this.userInfo.phone);
      this.$set(this.addAndEditFormData, "idCard", this.userInfo.idCard);
      this.$set(this.addAndEditFormData, "headImg", this.userInfo.headImg);
    },

    // 监听班级选择
    stuClassChange(value) {
      this.addAndEditFormData.classId = value[value.length - 1];
    },

    // 提交修改的用户信息
    handleConfirmEvent() {
      this.addAndEditDialogFormVisible = false;
      let parma = this.addAndEditFormData;
      this.api.putApi("/manager/stu/update", parma).then(res => {
        this.loginOut();
      });
    },

    // 取消提交修改的用户信息
    handleDialogClose() {
      this.addAndEditDialogFormVisible = false;
    },

    // 退出系统
    loginOut() {
      this.$confirm("是否退出系统?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          this.api.getApi("/logout").then(e => {
            if (e.data.code === 200) {
              localStorage.clear();
              this.$router.push("/login");
            } else {
              Message.info("系统出现问题");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消退出系统"
          });
        });
    },

    /**用户头像相关方法*/
    // 保存头像修改
    saveEditAvatar() {
      this.editAvatarDialog = false;
      this.finish("blob");
    },

    // 放大/缩小
    changeScale(num) {
      num = num || 1;
      this.$refs.cropper.changeScale(num);
    },

    // 左旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft();
    },

    // 右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight();
    },

    // 将base64的图片转换为file文件
    convertBase64UrlToBlob(urlData) {
      let bytes = window.atob(urlData.split(",")[1]); //去掉url的头，并转换为byte
      //处理异常,将ascii码小于0的转换为大于0
      let ab = new ArrayBuffer(bytes.length);
      let ia = new Uint8Array(ab);
      for (var i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
      }
      return new Blob([ab], { type: "image/jpeg" });
    },

    // 保存上传图片
    finish(type) {
      if (type === "blob") {
        this.$refs.cropper.getCropBlob(data => {
          this.avatarURL = window.URL.createObjectURL(data);
          let da = new FormData();
          da.append("file", data, this.fileName);
          this.api
            .postApi("/document/formData", da, {
              contentType: false,
              processData: false,
              headers: { "Content-Type": "application/x-www-form-urlencoded" }
            })
            .then(e => {
              if (e.data === null || e.data === "") {
                Message.error("保存失败，请重试");
              } else {
                // 更新用户表
                this.$set(this.addAndEditFormData, "id", this.userInfo.id);
                this.$set(this.addAndEditFormData, "name", this.userInfo.name);
                this.$set(
                  this.addAndEditFormData,
                  "classId",
                  this.userInfo.classId
                );
                this.$set(
                  this.addAndEditFormData,
                  "phone",
                  this.userInfo.phone
                );
                this.$set(
                  this.addAndEditFormData,
                  "idCard",
                  this.userInfo.idCard
                );
                this.$set(this.addAndEditFormData, "headImg", e.data);
                this.handleConfirmEvent();
              }
            });
        });
      } else {
        this.$refs.cropper.getCropData(data => {
          this.avatarURL = window.URL.createObjectURL(data);
        });
      }
    },

    // 实时预览函数
    realTime(data) {
      this.previews = data;
    },

    // 下载图片
    down(type) {
      var aLink = document.createElement("a");
      aLink.download = "author-img";
      if (type === "blob") {
        this.$refs.cropper.getCropBlob(data => {
          aLink.href = window.URL.createObjectURL(data);
          aLink.click();
        });
      } else {
        this.$refs.cropper.getCropData(data => {
          aLink.href = data;
          aLink.click();
        });
      }
    },

    // 更换头像--上传本地图片
    uploadImg(file) {
      var _this = this;
      this.fileName = file.name;
      var reader = new FileReader();
      reader.onload = e => {
        let data;
        if (typeof e.target.result === "object") {
          // 把Array Buffer转化为blob 如果是base64不需要
          data = window.URL.createObjectURL(new Blob([e.target.result]));
        } else {
          data = e.target.result;
        }
        _this.option.img = data;
      };
      reader.readAsArrayBuffer(file.raw);
    }
  }
};
</script>

<style scoped>
.header-style {
  text-align: right;
  font-size: 12px;
  /* background-color: #464c5b; */
  height: 50px;
}
.title-logo {
  height: 50px;
  width: 400px;
  /* background-color: #464c5b; */
  position: absolute;
}

.menu-ico {
  color: #606266;
}

.title-logo img {
  width: 40px;
  height: 40px;
  margin: 10px 5px 10px 25px;
}

.title-logo h3 {
  position: absolute;
  top: -7px;
  margin-left: 75px;
  color: white;
}

.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
}

.nameClass {
  color: #f7f7f7;
  float: right;
  margin-top: 10px;
  margin-left: 8px;
  font-family: "微软雅黑 Light", sans-serif;
  font-size: 18px;
}

.hideIcon {
  font-size: 23px;
  color: #e7efee;
  margin: 5px 35%;
}

.imgTitle {
  /*margin-top: 6px;*/
}

.top-right {
  margin-top: 5px;
  cursor: pointer;
  float: left;
  margin-left: 15px;
}

.top-home {
  float: right;
  margin-top: 9px;
  margin-right: 20px;
}

.top-exit {
  float: right;
  margin-top: 9px;
  margin-left: 15px;
  margin-right: 20px;
  cursor: pointer;
}

/*用户头像修改*/
.previewBox {
  text-align: center;
  margin-left: 50px;
}

.preview {
  width: 150px;
  height: 150px;
  margin: 0 auto 20px auto;
  border-radius: 50%;
  border: 1px solid #ccc;
  background-color: #ccc;
  overflow: hidden;
}

.cropper {
  width: 260px;
  height: 260px;
}

.content-style {
  background-color: white;
  /* height: 96%; */
  padding: 15px;
}
</style>
